package com.pdf.pdfserver.util;

import com.itextpdf.text.*;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import com.pdf.pdfserver.enums.WaterMarkEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Optional;

/**
 * @Author songfz
 * @Description
 * @Date 2022/1/20
 */
public class PdfWaterMarkUtil {

    private static Logger LOG = LoggerFactory.getLogger(PdfWaterMarkUtil.class);


    /**
     * 加水印
     *
     * @param inPath        原PDF文件地址
     * @param outPath       输出文件地址
     * @param ownerPassword 文件所有者密码
     * @param mark          文字水印
     * @param markImagePath 图片水印
     * @param waterMarkEnum 水印类型
     * @return
     */
    public static  boolean addWaterMark(String inPath, String outPath, String ownerPassword, String mark, String markImagePath, WaterMarkEnum waterMarkEnum) {

        if (WaterMarkEnum.TEXT.compareTo(waterMarkEnum) == 0) {
            return waterMarkText(inPath, outPath, ownerPassword, mark);
        } else if (WaterMarkEnum.IMAGE.compareTo(waterMarkEnum) == 0) {
            return waterMarkImage(inPath, outPath, ownerPassword, markImagePath);
        } else {
            return true;
        }
    }

    private static boolean waterMarkText(String inPath, String outPath, String ownerPassword, String mark) {
        PdfContentByte under;
          int interval = -5;
        PdfStamper stamp = null;
        Rectangle pageRect = null;
        try {
            PdfReader reader = new PdfReader(inPath, ownerPassword.getBytes());
            stamp = new PdfStamper(reader, new FileOutputStream(outPath));

            stamp.setEncryption(null, ownerPassword.getBytes(), PdfWriter.ALLOW_PRINTING, PdfWriter.STANDARD_ENCRYPTION_128);;

            // 原pdf文件的总页数
            int pageSize = reader.getNumberOfPages();
            PdfGState gs1 = new PdfGState();

            JLabel label = new JLabel();
            FontMetrics metrics;
            int textH = 0;
            int textW = 0;
            label.setText(mark);
            metrics = label.getFontMetrics(label.getFont());
            textH = metrics.getHeight();
            textW = metrics.stringWidth(label.getText());
            // 透明度设置
            gs1.setFillOpacity(0.7f);
            for (int i = 1; i <= pageSize; i++) {
                pageRect = reader.getPageSizeWithRotation(i);
                // 水印在之前文本下
//                under = stamp.getUnderContent(i);
                //水印在之前文本上
                under = stamp.getOverContent(i);
                under.saveState();
                under.beginText();
                // 文字水印 颜色
                under.setColorFill(new BaseColor(28, 28, 28));
                // 文字水印 字体及字号
                under.setFontAndSize(PdfConvertUtil.baseFont(), 10);
                under.setGState(gs1);
                // 文字水印 起始位置
                under.setTextMatrix(20, 50);
                //under.showTextAligned(Element.ALIGN_LEFT, mark, 250, 550, 45);
                //循环铺满整个版面水印
                for (int height = interval + textH; height < pageRect.getHeight();
                     height = height + textH*3) {
                    for (int width = interval + textW; width < pageRect.getWidth() + textW;
                         width = width + textW*2) {
                        under.showTextAligned(Element.ALIGN_LEFT
                                , mark, width - textW,
                                height - textH, 30);
                    }
                }
                under.endText();
            }
            return true;
        } catch (IOException | DocumentException e) {
            LOG.error(e.getMessage(), e);
            return false;
        } finally {
            Optional.ofNullable(stamp).ifPresent(stamp1 -> {
                try {
                    stamp1.close();
                } catch (DocumentException | IOException e) {
                    LOG.error(e.getMessage(), e);
                }
            });
        }

    }


    private static boolean waterMarkImage(String inPath, String outPath, String ownerPassword, String markImagePath) {
        PdfContentByte under;
        PdfStamper stamp = null;
        try {
            PdfReader reader = new PdfReader(inPath,ownerPassword.getBytes());

            stamp = new PdfStamper(reader, new FileOutputStream(new File(outPath)));

            stamp.setEncryption(null, ownerPassword.getBytes(), PdfWriter.ALLOW_PRINTING, PdfWriter.STANDARD_ENCRYPTION_128);
            PdfGState gs1 = new PdfGState();
            // 透明度设置
            gs1.setFillOpacity(0.3f);
            // 插入图片水印
            Image img = Image.getInstance(markImagePath);
            // 坐标
            img.setAbsolutePosition(50, 120);
            // 旋转 弧度
            img.setRotation(-20);
            // 旋转 角度
            img.setRotationDegrees(45);
            // 自定义大小
            img.scaleAbsolute(500, 250);
            // img.scalePercent(50);//依照比例缩放
            // 原pdf文件的总页数
            int pageSize = reader.getNumberOfPages();
            for (int i = 1; i <= pageSize; i++) {
                // 水印在之前文本下
                under = stamp.getUnderContent(i);
                //水印在之前文本上
                // under = stamp.getOverContent(i);
                // 图片水印 透明度
                under.setGState(gs1);
                // 图片水印
                under.addImage(img);
            }
            return true;

        } catch (IOException | DocumentException e) {
            LOG.error(e.getMessage(), e);
            return false;
        } finally {
            Optional.ofNullable(stamp).ifPresent(stamp1 -> {
                try {
                    stamp1.close();
                } catch (DocumentException | IOException e) {
                    LOG.error(e.getMessage(), e);
                }
            });
        }

    }
}
